import { useState, useEffect } from 'react';
import { Popup, Picker } from 'react-vant';

import SvgIcon from '@/components/SvgIcon/index';

import {
  staticActionList, timeColumn, tempColumn, deviceId, ActionKey, IColumeItem
} from '@/utils/staticData';
import { IActionData } from '@/types/IContext';
import useStore from '@/store/index';

import './index.less';

interface ActionProps {
  onActionChange: (value: string, type: ActionKey) => void;
}

console.log(tempColumn(), 'tempColumn', Array.isArray(tempColumn()));


const CONSTANTS = {
  TEMP: {
    key: 'temperature',
    title: '烹饪温度',
    unit: '℃',
    paramName: 'temperature'
  },
  TIME: {
    key: 'time',
    title: '烹饪时间',
    unit: '分钟',
    paramName: 'time'
  }
} as const;

export default function Action({ onActionChange }: ActionProps) {
  const Hejia = (window as any).Hejia;
  const { startLoop, stopLoop, info } = useStore();
  const { isOnline, time, temperature, mode, fault, state, prompt } = info

  const [visibleStr, setVisibleStr] = useState<string>('');
  const [disabledList, setDisabledList] = useState<string[]>(['']);
  const [timeValue, setTimeValue] = useState<string[]>([`${time}`]);
  const [tempValue, setTempValue] = useState<string[]>([`${temperature}`]);

  let _staticActionList = staticActionList;

  const tempVisible = 'temperature'
  const timeVisible = 'time'


  const getDisabled = (): void => {
    if (!isOnline || fault > 0 || prompt > 0 || [2].includes(state)) {
      setDisabledList(['temperature', 'time']);
    } else {
      setDisabledList(['']);
    }
  };

  useEffect(() => {
    getDisabled();
  }, [isOnline, mode, fault, state]);

  // 烹饪温度
  useEffect(() => {
    setTempValue([`${temperature}`]);
    _staticActionList[0].val = temperature ? `${temperature}℃` : '未设置';
  }, [temperature]);

  // 烹饪时间
  useEffect(() => {
    setTimeValue([`${time}`]);
    _staticActionList[1].val = time ? `${time}分钟` : '未设置';
  }, [time]);

  const onClose = () => {
    setVisibleStr('');
    setTimeout(() => {
      startLoop();
    }, 2000);
  };
  const onOpen = () => {
    stopLoop();
  };

  const onClickAction = (key: string): void => {
    setVisibleStr(key);
  };

  const itemEle = _staticActionList.map((item: IActionData) => {
    return (
      <div className="action-item" key={item.id}>
        {disabledList.includes(item.key) && <div className="mask"></div>}
        <div className="content" onClick={() => onClickAction(item.key)}>
          <div className="icon">
            <SvgIcon name={`${item.svg}`} size="34" />
          </div>
          <div className="left">
            <div className="title">{item.title}</div>
            <div className="num">{item.val}</div>
          </div>
        </div>
      </div>
    );
  });

  const handleConfirm = (val: string, type: ActionKey, index: number) => {
    const config = type === 'temperature' ? CONSTANTS.TEMP : CONSTANTS.TIME;
    _staticActionList[index].val = `${val}${config.unit}`;
    console.log('handleConfirm:', val, typeof val, type, index);
    onActionChange(val, type);
    onClose();

    Hejia.setControlParam(
      {
        // deviceId,
        parameters: {
          param: [
            {
              name: config.paramName,
              content: val
            }
          ]
        }
      },
      () => console.log('success'),
      (msg: string, obj: any) => console.log(msg + obj.resultCode + obj.resultCodeMessage)
    );
  };

  const renderPickerPopup = (
    visible: boolean,
    value: string[],
    title: string,
    columns: () => IColumeItem[],
    type: ActionKey,
    index: number,
    unit: string
  ) => (
    <Popup
      round
      visible={visible}
      position="bottom"
      onOpen={onOpen}
      onClose={onClose}
    >
      <div className="time-wrapper">
        <Picker
          value={value}
          title={title}
          placeholder=""
          confirmButtonText="确定"
          columns={columns()}
          onCancel={() => setVisibleStr('')}
          onConfirm={(val: any) => handleConfirm(val, type, index)}
        />
        <div className="unit">{unit}</div>
      </div>
    </Popup>
  );

  return (
    <div className="action">
      {itemEle}

      {renderPickerPopup(
        tempVisible === visibleStr,
        tempValue,
        CONSTANTS.TEMP.title,
        tempColumn,
        'temperature',
        0,
        CONSTANTS.TEMP.unit
      )}

      {renderPickerPopup(
        timeVisible === visibleStr,
        timeValue,
        CONSTANTS.TIME.title,
        timeColumn,
        'time',
        1,
        CONSTANTS.TIME.unit
      )}
    </div>
  );
}
